import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:jxchmz/%E8%93%9D%E7%89%99/BleManager.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';

import '../../BleModel.dart';
import '../../Setting.dart';

class GoodsInventory extends StatefulWidget {
  @override
  _GoodsInventoryState createState() => new _GoodsInventoryState();
}

class _GoodsInventoryState extends State<GoodsInventory> {
  //盘点单编号
  var BillNo;

  //单据数据
  var arguments;
  //实际盘点列表
  var EPCList = [];
  //需要盘点的列表
  var DataList = [];
  //是否读取标识
  var IsRead = false;
  //去重用的数组,防止重复请求
  var EPCListRequest = [];
  //用于回复数据的数组
   List ClearData = [];
  BluetoothCharacteristic? _bluetoothCharacteristicFFF1 ;
  BluetoothCharacteristic? _bluetoothCharacteristicFFF2 ;
  var IsConnect = false;
//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //获取上个页面传参
    arguments = Get.arguments['Order'];
    BillNo = arguments['billNo'];
    //获取需要盘点的列表
    DataList = arguments['InfoList'];
    ClearData = json.decode(json.encode(arguments['InfoList']));
    print("恢复数据:$ClearData");
    print("需要盘点的数量:${DataList.length}");
    Future.delayed(Duration.zero,() async {
      //获取连接池
      List<BluetoothDevice>? devideList =await  BleManager.instance.getConnectedDevices();
      GetStorage getStorage = new GetStorage();
      if(devideList!.length>0){
        IsConnect = true;
        _bluetoothCharacteristicFFF1 = BleModel.BletoothCharacteristicFFF1;
        _bluetoothCharacteristicFFF2 = BleModel.BletoothCharacteristicFFF2;

        //设置监听蓝牙数据
        _characteristicFFF4SetNotify();

      }else{
        IsConnect = false;
        //弹窗阻止
        ShowNo();
      }

    });
    setState(() {
    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(IsConnect){
      _bluetoothCharacteristicFFF1!.setNotifyValue(false);
      BleManager.instance.CancelListen();
    }
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text("Inventorydetails".tr, style: TextStyle(fontSize: 15, color: Colors.black),),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(
              color: Colors.black
          ),
          actions: [
            IconButton(onPressed: (){
              if(IsRead){
                //停止读取
                IsRead = false;
                List<int> WritData = [0x40,0x02,0xE1,0x00];
                int Check = checkSum(WritData);
                WritData.add(Check);
                WriteBle(WritData);
              }
              setState(() {
              });
              //功率调整
              _bluetoothCharacteristicFFF1!.setNotifyValue(false);
              Get.to(Setting())!.then((value){
                print("返回数据");
                //设置页面返回的数据
                // 重新监听蓝牙
                _bluetoothCharacteristicFFF1!.setNotifyValue(true);
              });
            }, icon: Icon(Icons.settings)),
            IconButton(onPressed: (){
              ShowUpload();

            }, icon: Icon(Icons.cloud_upload)),
          ],
        ),
        body: Container(
          padding: EdgeInsets.all(15),
          child: Column(
            children: [
              //表单信息

              Container(
                alignment: Alignment.centerLeft,
                child: Text("Inventorynumber".tr+":$BillNo"),
              ),
              Container(
                height: 5,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("Plannedinventoryquantity".tr+":${arguments['countQuantity']}"),
                  Text("Actualinventoryquantity".tr+":${arguments['countedQuantity']}")
                ],
              ),
              Container(
                height: 5,
              ),
              Container(
                alignment: Alignment.centerLeft,
                child: Text("Inventorywarehouse".tr+":${arguments['warehouseIdName']}"),
              ),
              Container(
                margin: EdgeInsets.only(top: 15),
                alignment: Alignment.centerLeft,
                child: Text(
                  "InventoryList".tr+"(${EPCList.length})",
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 17),
                ),
              ),
              Expanded(
                child: ListView.separated(
                  itemCount: DataList.length,
                  itemBuilder: (context,index){
                    return Container(
                      child: ListTile(
                        title: Container(
                          margin: EdgeInsets.only(top: 10),
                          child: Text("${DataList[index]['rfidCode']}",style: TextStyle(fontSize: 13),),
                        ),
                        subtitle: Column(
                         crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("Itemcategory".tr+":${DataList[index]['jxcMaterialCategoryIdName']}"),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("material".tr+":${DataList[index]['materialIdName']}"),
                              Text("unit".tr+":${DataList[index]['unitIdName']}")
                            ],
                          )
                          ],
                        ),
                        trailing: Text(DataList[index]['checkStatus']==0? "Notcounted".tr:"Counted".tr,style: TextStyle(color: DataList[index]['checkStatus']==0?Colors.red:Colors.green),),
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Divider();
                  },
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    MaterialButton(
                      child: Text(
                        "Clearthedata".tr,
                        style: TextStyle(color: Colors.white),
                      ),
                      minWidth: MediaQuery.of(context).size.width / 3,
                      color: Colors.orange,
                      shape: const RoundedRectangleBorder(
                        //边框圆角
                        borderRadius: BorderRadius.all(
                          Radius.circular(20),
                        ),
                      ),
                      onPressed: () {
                        //清空本地缓存，前往登录页面
                        Get.defaultDialog(
                            title: "prompt".tr,
                            middleText: "Areyousureyouwanttoclearthereadlist".tr,
                            barrierDismissible: false,
                            confirm: MaterialButton(
                              onPressed: () async {
                                Get.back();
                                //清空数据
                                Clear();
                              },
                              child: Text("sure".tr,style: TextStyle(color: Colors.white),),
                              color: Color(0xff372D9F),
                            ),
                            cancel: MaterialButton(
                              onPressed: () {
                                Get.back();
                              },
                              child: Text(
                                "Cancel".tr,
                                style: TextStyle(color: Color(0xff372D9F)),
                              ),
                              color: Colors.white,
                              //边框样式
                              shape: const RoundedRectangleBorder(
                                //边框颜色
                                side: BorderSide(
                                  color: Color(0xff372D9F),
                                  width: 1,
                                ),
                              ),
                            ));

                      },
                    ),
                    MaterialButton(
                      child: Text(IsRead ? "Stopreading".tr : "Startreading".tr, style: TextStyle(color: Colors.white)),
                      minWidth: MediaQuery.of(context).size.width / 2 ,
                      color: IsRead ? Colors.red : Colors.blue,
                      shape: const RoundedRectangleBorder(
                        //边框圆角
                        borderRadius: BorderRadius.all(
                          Radius.circular(20),
                        ),
                      ),
                      onPressed: () {
                        if(IsRead){
                          //停止读取
                          IsRead = false;
                          List<int> WritData = [0x40,0x02,0xE1,0x00];
                          int Check = checkSum(WritData);
                          WritData.add(Check);
                          WriteBle(WritData);
                        }else{
                          //开始读取
                          IsRead = true;
                          List<int> WritData = [0x40,0x02,0xE1,0x01];
                          int Check = checkSum(WritData);
                          WritData.add(Check);
                          WriteBle(WritData);
                        }
                        setState(() {
                        });
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
    );
  }
  //监听特征上报数据
  _characteristicFFF4SetNotify() async {
    await   _bluetoothCharacteristicFFF1!.setNotifyValue(true);
    // ignore: missing_return
    BleManager.instance.listenCharacteristicValue(_bluetoothCharacteristicFFF1!, (data) async {
      if (data == null) {
        print("data=null>>>>>>");
        return;
      }
      //解析蓝牙数据，转为十六进制
      String DataHex =await _BleDataCallback(data);
      List dataList = DataHex.split(",");

      if(dataList[0]=="f0"&&dataList[2]=="e1"){
        print("DataHex=>>>>>>$DataHex");
        print("dataList=>>>>>>$dataList");
        print("是epc");
        //这里面写调用逻辑
        //拿epc数据
        //判断EPC长度
        int Len = _hexToInt(dataList[1].toString());
        print("EPC数据长度:$Len");
        String EPC = dataList.sublist(3,Len+1).join("");
        print("epc:$EPC");
        if(!EPCListRequest.contains(EPC)){
          EPCListRequest.add(EPC);
          //查询标签信息是否在库内
          // await SearchRFID(EPC);
          //和需要盘点的列表对比
          DataList.forEach((element) {
            if(element['rfidCode']==EPC){
              element['checkStatus']=1;
              print("匹配到了EPC，进行更改状态为已盘点:$element");
            }
          });
          setState(() {
          });
        }

      }
      if(DataHex.contains("f1,03,01")){
        print("录入页面蓝牙数据");
        //  读卡状态
        if(DataHex.contains("f1,03,01,00")){
          //停止读卡
          IsRead = false;
        }else{
          IsRead = true;
        }
      }
      if (mounted) {
        setState(() {
        });
      }
    });

  }
  //  发送请求
  void WriteBle(WritData) {
    // print("发送的蓝牙数据:${WritData}");
    BleManager.instance.characteristicToWriteValue(_bluetoothCharacteristicFFF2!, WritData).then((value) => print("write result:$value"));
  }
  //解析蓝牙数据
  _BleDataCallback(value) async {
    List data = [];
    for (var i = 0; i < value.length; i++) {
      String dataStr = value[i].toRadixString(16);
      if (dataStr.length < 2) {
        dataStr = "0" + dataStr;
      }
      String dataEndStr =  dataStr;
      data.add(dataEndStr);
    }
    return data.join(",");
  }
  //校验位
  int checkSum(List<int> buffer) {
    int sum = 0;
    for (int i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    sum = (~sum) + 1;
    return sum;
  }
  //十六进制转十进制
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }
  //没有连接蓝牙，弹窗阻止
  ShowNo(){
    Get.defaultDialog(
      title: "prompt".tr,
      middleText: "PleaseconnectaBluetoothdevice".tr,
      barrierDismissible: false,
      confirm: MaterialButton(
        onPressed: () async {
          Get.back();
          Get.back();
        },
        child: Text("sure".tr,style: TextStyle(color: Colors.white),),
        color: Color(0xff372D9F),
      ),
    );
  }
//  清空数据
  Clear(){

    EPCList.clear();
    EPCListRequest.clear();
    //获取需要盘点的列表
    // DataList.forEach((element) {
    //   element['checkStatus']=0;
    // });

    DataList = ClearData;
    print("恢复数据:$ClearData");
    print("数据数组:$DataList");
    setState(() {
    });
  }
  //查询标签信息是否在库内
  SearchRFID(EPC) async {
    print("开始请求获取标签信息");
    var data = {
      "rfidCode":EPC,
    };
    var ResultData = await new KuCunManager().SearchEPC(data);
    if(ResultData['code'] == 200){
      if(ResultData['total']!=0){
        EPCList.add(EPC);

      }
    }else {
    }
    EPCList= EPCList.toSet().toList();
    setState(() {});
  }
  ShowUpload(){
    Get.defaultDialog(
        title: "prompt".tr,
        middleText: "Areyousureyouwanttosubmitthisdata".tr,
        barrierDismissible: false,
        confirm: MaterialButton(
          onPressed: () async {
            Get.back();
            KSProgressDialog().LoadingToast("Submitting".tr, context);
            UploadConfrim();
          },
          child: Text("sure".tr,style: TextStyle(color: Colors.white),),
          color: Color(0xff372D9F),
        ),
        cancel: MaterialButton(
          onPressed: () {
            Get.back();
          },
          child: Text(
            "Cancel".tr,
            style: TextStyle(color: Color(0xff372D9F)),
          ),
          color: Colors.white,
          //边框样式
          shape: const RoundedRectangleBorder(
            //边框颜色
            side: BorderSide(
              color: Color(0xff372D9F),
              width: 1,
            ),
          ),
        ));
  }
  //提交盘点数据
  UploadConfrim() async {
    var data ;
    var List = [];
    DataList.forEach((element) {
      if(element['checkStatus']==1){
    List.add(element);
      }
    });
    data = {
      "InfoList":List,
      "billNo":BillNo,
      "countQuantity":arguments['countQuantity'],
      "countedQuantity":List.length,
      "id":arguments['id']
    };
    var ResultData = await new KuCunManager().UploadInventoryData(data);
    KSProgressDialog().CloseLoading();
    if(ResultData['code'] == 200){
      // Get.back();
      GetxTools().SuccessToast("Thesubmissionwassuccessful".tr);
      // Clear();

    }else {
      GetxTools().ErrorToast("Commitfailed".tr);
    }
    setState(() {});
  }

}
